package expe.seven;

import java.util.Scanner;

class BuyTicketPerson {
    private static int sum;
    public static int getSum() {
        return sum;
    }
    public static void setSum(int sum) {
        BuyTicketPerson.sum = sum;
    }
}

class HarbinTrainStation {
    volatile private static int ticketSum = 2000;
    public static int getTicketSum() {
        return ticketSum;
    }
    public static void setTicketSum(int ticketSum) {
        HarbinTrainStation.ticketSum = ticketSum;
    }
}


class Sale implements Runnable {
    public void sell() throws InterruptedException {
        for (int i = 0 ;; i++) {
            Thread.sleep(2000,0);
            synchronized (this) {
                if (BuyTicketPerson.getSum() > 0) {
                    if (HarbinTrainStation.getTicketSum() > 0) {
                        HarbinTrainStation.setTicketSum(HarbinTrainStation.getTicketSum() - 1);
                        System.out.println(Thread.currentThread().getName() + "卖出去了一张票，火车站还剩" + HarbinTrainStation.getTicketSum() + "张票");
                    } else {
                        break;
                    }
                    BuyTicketPerson.setSum(BuyTicketPerson.getSum() - 1);
                }
                else
                    break;
            }
        }
    }
    @Override
    public void run() {
        try {
            sell();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

public class Rg7180 {
    public static void main(String[] args) throws InterruptedException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("买票的人共有：");
        BuyTicketPerson.setSum(scanner.nextInt());
        System.out.println("火车站总票数为：");
        HarbinTrainStation.setTicketSum(scanner.nextInt());
        Sale sale = new Sale();

        Thread threadha = new Thread(sale, "哈站");
        Thread threadhaxi = new Thread(sale, "哈西站");
        Thread threadhadong = new Thread(sale, "哈东站");

        threadha.start();
        threadhaxi.start();
        threadhadong.start();

        threadha.join();
        threadhadong.join();
        threadhaxi.join();

        if (HarbinTrainStation.getTicketSum()>0) {
            System.out.println("票没卖完，所有人都买到了票，还剩" + HarbinTrainStation.getTicketSum() + "张");
        }
        if (HarbinTrainStation.getTicketSum()==0){
            if(BuyTicketPerson.getSum()==0) {
                System.out.println("票卖完了，且所有人都买到了票");
            }
            else{
                System.out.println("票卖完了，有剩余" + BuyTicketPerson.getSum() + "人没买到票");
            }
        }
    }

}
